function toSelTreeData(data) {
  const resData = data;
  const tree = [];

  function run(chiArr) {
    if (resData.length !== 0) {
      for (let i = 0; i < chiArr.length; i += 1) {
        for (let j = 0; j < resData.length; j += 1) {
          if (chiArr[i].key === resData[j].parentOrgId) {
            const obj = {
              key: resData[j].orgId,
              value: resData[j].orgCode,
              text: resData[j].orgName,
              children: []
            };
            chiArr[i].children.push(obj);
            resData.splice(j, 1);
            j -= 1;
          }
        }

        run(chiArr[i].children);
      }
    }
  }

  if (resData) {
    for (let i = 0; i < resData.length; i += 1) {
      if (resData[i].parentOrgId === "0") {
        const obj = {
          key: resData[i].orgId,
          value: resData[i].orgCode,
          text: resData[i].orgName,
          children: []
        };
        tree.push(obj);
        resData.splice(i, 1);
        i -= 1;
      }
    }
    run(tree);
  }

  return tree;
}

export default toSelTreeData;
